import java.util.LinkedList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 98152
 * Date: 2024-12-12
 * Time: 18:47
 */
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    public TreeNode(int val) {
        this.val = val;
    }
}
public class Solution {
    private List<String> lists;
    public List<String> binaryTreePaths(TreeNode root) {
        lists = new LinkedList<String>();
        StringBuffer strBuff = new StringBuffer();
        dfs(root, strBuff);
        return lists;
    }
    private void dfs(TreeNode root, StringBuffer path) {
        if(root == null) return;
        if(path.length() > 0) path.append("->");
        path.append(root.val);
        if(root.left == null && root.right == null) {
            lists.add(path.toString());
        } else {
            dfs(root.left, path);
            dfs(root.right, path);
        }

        //回溯
        int lastIndex = path.lastIndexOf(String.valueOf(root.val)) - 2;
        if(lastIndex >= 0) {
            path.delete(lastIndex, path.length());
        }
    }
}
